package user

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"oa-rest/common"
	"oa-rest/middleware"
	"path/filepath"
	"sort"
	"strings"

	"github.com/dchest/captcha"
	"github.com/gin-gonic/gin"
)

func (s *User) LoginHandler(c *gin.Context) {
	prm := &UsUser{}
	var err error
	_ = err
	err = c.ShouldBind(prm)
	if err != nil {
		log.Println("LoginHandler[c.ShouldBind] :", err.Error())
		c.String(http.StatusBadRequest, err.Error())
		return
	}

	queryUser := &UsUser{UserName: prm.UserName}
	err = queryUser.QueryByName(s.db)
	if err != nil {
		log.Println("LoginHandler[prm.Login] :", err.Error())
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}
	if queryUser.Id == 0 {
		c.String(http.StatusServiceUnavailable, "该用户不存在！")
		return
	}
	if queryUser.Status == 2 {
		c.String(http.StatusServiceUnavailable, "该用户已被禁用！")
		return
	}

	if prm.FeiShuCode == "" {
		loginPass := prm.Password
		password := strings.ToUpper(common.EncodeMD5(loginPass))
		if password != queryUser.Password {
			c.String(http.StatusServiceUnavailable, "账户或密码错误！")
			return
		}
	}

	token, expired, err := middleware.GenerateToken(queryUser.Id, queryUser.UserName, queryUser.RealName, "")
	if err != nil {
		c.String(http.StatusServiceUnavailable, "Token生成失败!")
		return
	}
	prm.Token = token
	prm.Expired = expired
	prm.Password = ""
	prm.FormulaJurisdiction = queryUser.FormulaJurisdiction
	prm.UserOrgs = queryUser.UserOrgs
	prm.RealName = queryUser.RealName
	prm.QaFlag = queryUser.QaFlag

	fmt.Println(">>>>>>", prm.UserOrgs)

	//用户快捷菜单
	userMenu := &UsMenu{}
	err = userMenu.GetUserMenusByUserId(s.db, queryUser.Id)
	if err != nil {
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}
	menuAction := &UsMenuAction{}
	err = menuAction.getMenuAction(s.db)
	if err != nil {
		log.Println("GetMenuActionHandler[prm.GetMenuList] :", err.Error())
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}

	if prm.UserName == "admin" {
		menu := &UsMenu{}
		err = menu.GetAllMenuList(s.db, c)
		if err != nil {
			c.String(http.StatusServiceUnavailable, err.Error())
			return
		}
		for _, v := range menu.List {
			for _, m := range menuAction.List {
				if v.Id == m.MenuId {
					v.ActionList = append(v.ActionList, m)
				}
			}
		}
		menu.List = append(menu.List, userMenu.List...)
		prm.Menus = getMenusTree(menu.List)
	} else {
		menu := &UsMenu{}
		err = menu.GetMenusByUserId(s.db, queryUser.Id)
		if err != nil {
			c.String(http.StatusServiceUnavailable, err.Error())
			return
		}
		for _, v := range menu.List {
			for _, m := range menuAction.List {
				if v.Id == m.MenuId {
					v.ActionList = append(v.ActionList, m)
				}
			}
		}
		roleMenu := &UsRoleMenu{}
		err = roleMenu.GetRoleMenuByUserId(queryUser.Id, s.db)
		if err != nil {
			c.String(http.StatusServiceUnavailable, err.Error())
			return
		}
		tmpActList := make([]string, 0)

		for _, v := range menu.List {
			tmpActionList := make([]*UsMenuAction, 0)
			for _, rm := range roleMenu.List {
				if rm.MenuId == v.Id {
					if rm.MenuAction != "[]" && rm.MenuAction != "" {
						err = json.Unmarshal([]byte(rm.MenuAction), &tmpActList)
						if err != nil {
							c.String(http.StatusServiceUnavailable, err.Error())
							return
						}
						for _, an := range tmpActList {
							for _, m := range menuAction.List {
								if an == m.Name && m.MenuId == v.Id {
									tmpActionList = append(tmpActionList, m)
								}
							}
						}
					}
				}
			}
			v.ActionList = RemoveRepByLoop(tmpActionList)
		}
		menu.List = append(menu.List, userMenu.List...)
		prm.Menus = getMenusTree(menu.List)
	}
	prm.Menus = setMenuLevel(prm.Menus, 0)

	r, _ := json.Marshal(prm)
	log.Printf("JSON响应: %s", string(r))
	c.String(http.StatusOK, string(r))
}

func RemoveRepByLoop(slc []*UsMenuAction) []*UsMenuAction {
	result := []*UsMenuAction{} // 存放结果
	for i := range slc {
		flag := true
		for j := range result {
			if slc[i].Id == result[j].Id {
				flag = false // 存在重复元素，标识为false
				break
			}
		}
		if flag { // 标识为false，不添加进结果
			result = append(result, slc[i])
		}
	}
	return result
}

func (s *User) UpdPasswordHandler(c *gin.Context) {
	prm := &UsUser{}
	var err error
	_ = err
	err = c.ShouldBind(prm)
	if err != nil {
		log.Println("UpdPasswordHandler[c.ShouldBind] :", err.Error())
		c.String(http.StatusBadRequest, err.Error())
		return
	}
	if prm.UserName == "" || prm.Password == "" || prm.OldPassword == "" {
		c.String(http.StatusServiceUnavailable, "请求参数错误!")
		return
	}
	queryUser := &UsUser{UserName: prm.UserName}
	err = queryUser.QueryByName(s.db)
	if err != nil {
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}
	oldPass := common.EncodeMD5(prm.OldPassword)
	if queryUser.Password != strings.ToUpper(oldPass) {
		c.String(http.StatusServiceUnavailable, "原密码错误!")
		return
	}
	password := common.EncodeMD5(prm.Password)
	prm.Password = strings.ToUpper(password)
	err = prm.UpdPassword(s.db, c)
	if err != nil {
		log.Println("UpdPasswordHandler[prm.UpdPassword] :", err.Error())
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}
	r, _ := json.Marshal(prm)
	c.String(http.StatusOK, string(r))
}

func getMenusTree(data []*UsMenu) []*UsMenu {
	mi := make(map[int64]*UsMenu)
	for _, item := range data {
		item.Open = false
		item.Selected = false
		item.Disabled = false
		// item.Level = 1
		mi[item.Id] = item
	}
	var list []*UsMenu
	for _, item := range data {
		if item.Pid == 0 {
			list = append(list, item)
			continue
		}
		if pitem, ok := mi[item.Pid]; ok {
			if pitem.Children == nil {
				var children []*UsMenu
				// item.Level = pitem.Level + 1
				children = append(children, item)
				pitem.Children = children
				// 从小到大排序(稳定排序)
				sort.SliceStable(pitem.Children, func(i, j int) bool {
					if pitem.Children[i].Index < pitem.Children[j].Index {
						return true
					}
					return false
				})
				continue
			}
			pitem.Children = append(pitem.Children, item)
			// 从小到大排序(稳定排序)
			sort.SliceStable(pitem.Children, func(i, j int) bool {
				if pitem.Children[i].Index < pitem.Children[j].Index {
					return true
				}
				return false
			})
		}
	}
	// 从小到大排序(稳定排序)
	sort.SliceStable(list, func(i, j int) bool {
		if list[i].Index < list[j].Index {
			return true
		}
		return false
	})
	return list
}

func setMenuLevel(data []*UsMenu, level int64) []*UsMenu {
	for _, v := range data {
		v.Level = level + 1
		if len(v.Children) > 0 {
			v.Children = setMenuLevel(v.Children, v.Level)
		}
	}
	return data
}

func (s *User) GetAllMenuTreeHandler(c *gin.Context) {
	prm := &UsMenu{}
	var err error
	_ = err
	err = c.ShouldBind(prm)
	if err != nil {
		log.Println("GetAllMenuTreeHandler[c.ShouldBind] :", err.Error())
		c.String(http.StatusBadRequest, err.Error())
		return
	}
	err = prm.GetAllMenuTree(s.db, c)
	if err != nil {
		log.Println("GetAllMenuTreeHandler[prm.GetAllMenuTree] :", err.Error())
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}

	menuAction := &UsMenuAction{}
	err = menuAction.getMenuAction(s.db)
	if err != nil {
		log.Println("GetMenuActionHandler[prm.GetMenuList] :", err.Error())
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}

	for _, v := range prm.List {
		for _, m := range menuAction.List {
			if v.Id == m.MenuId {
				v.ActionList = append(v.ActionList, m)
			}
		}
	}

	prm.List = getMenusTree(prm.List)
	prm.List = setMenuLevel(prm.List, 0)
	r, _ := json.Marshal(prm)
	c.String(http.StatusOK, string(r))
}

func (s *User) RefreshTokenHandler(c *gin.Context) {
	prm := &TokenInfo{}
	var err error
	_ = err
	err = c.ShouldBind(prm)
	if err != nil {
		log.Println("RefreshTokenHandler[c.ShouldBind] :", err.Error())
		c.String(http.StatusBadRequest, err.Error())
		return
	}
	if prm.Token == "" {
		c.String(http.StatusServiceUnavailable, "请求参数错误!")
		return
	}
	token, exp, err := middleware.RefreshToken(prm.Token)
	if err != nil {
		c.String(http.StatusBadRequest, err.Error())
		return
	}
	prm.Token = token
	prm.Expired = exp
	r, _ := json.Marshal(prm)
	c.String(http.StatusOK, string(r))
}

func (s *User) GetCaptchaHandler(c *gin.Context) {
	prm := &CaptchaResponse{}
	var err error
	_ = err
	err = c.ShouldBind(prm)
	if err != nil {
		log.Println("GetCaptchaHandler[c.ShouldBind] :", err.Error())
		c.String(http.StatusBadRequest, err.Error())
		return
	}
	out := &CaptchaResponse{}
	captchaId := captcha.NewLen(4)
	out.CaptchaId = captchaId
	out.ImageUrl = "user/captcha/" + captchaId + ".png"
	r, _ := json.Marshal(out)
	c.String(http.StatusOK, string(r))
}

func (s *User) UpdUserHandler(c *gin.Context) {
	prm := &UsUser{}
	var err error
	_ = err
	err = c.ShouldBind(prm)
	if err != nil {
		log.Println("UpdUserHandler[c.ShouldBind] :", err.Error())
		c.String(http.StatusBadRequest, err.Error())
		return
	}
	if prm.Id == 0 {
		c.String(http.StatusServiceUnavailable, "请求参数错误")
		return
	}
	err = prm.UpdUserOw(s.db)
	if err != nil {
		log.Println("UpdUserHandler[prm.UpdUser] :", err.Error())
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}
	r, _ := json.Marshal(prm)
	c.String(http.StatusOK, string(r))
}

func (s *User) AddUserHandler(c *gin.Context) {
	prm := &UsUser{}
	var err error
	_ = err
	err = c.ShouldBind(prm)
	if err != nil {
		log.Println("AddUserHandler[c.ShouldBind] :", err.Error())
		c.String(http.StatusBadRequest, err.Error())
		return
	}
	queryUser := &UsUser{UserName: prm.UserName}
	err = queryUser.QueryByName(s.db)
	if err != nil {
		c.String(http.StatusBadRequest, err.Error())
		return
	}
	if queryUser.Id > 0 {
		c.String(http.StatusServiceUnavailable, "该用户已存在!")
		return
	}
	prm.Password = common.EncodeMD5("Gb123456!") //默认初始密码000000
	prm.Password = strings.ToUpper(prm.Password)
	prm.Status = 1
	err = prm.AddUserOw(s.db)
	if err != nil {
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}
	r, _ := json.Marshal(prm)
	c.String(http.StatusOK, string(r))
}

func (s *User) AddRoleHandler(c *gin.Context) {
	prm := &UsRole{}
	var err error
	_ = err
	err = c.ShouldBind(prm)
	if err != nil {
		log.Println("AddRoleHandler[c.ShouldBind] :", err.Error())
		c.String(http.StatusBadRequest, err.Error())
		return
	}
	queryRole := &UsRole{Name: prm.Name}
	err = queryRole.GetRoleByName(s.db, c)
	if err != nil {
		c.String(http.StatusBadRequest, err.Error())
		return
	}
	if queryRole.Id > 0 {
		c.String(http.StatusServiceUnavailable, "该角色名称已存在！")
		return
	}
	err = prm.AddRoleOw(s.db)
	if err != nil {
		c.String(http.StatusBadRequest, err.Error())
		return
	}
	r, _ := json.Marshal(prm)
	c.String(http.StatusOK, string(r))
}

func (s *User) UpdRoleHandler(c *gin.Context) {
	prm := &UsRole{}
	var err error
	_ = err
	err = c.ShouldBind(prm)
	if err != nil {
		log.Println("UpdRoleHandler[c.ShouldBind] :", err.Error())
		c.String(http.StatusBadRequest, err.Error())
		return
	}
	if prm.Id == 0 {
		c.String(http.StatusBadRequest, "参数错误！")
		return
	}
	queryRole := &UsRole{Id: prm.Id, Name: prm.Name}
	err = queryRole.GetRoleByName(s.db, c)
	if err != nil {
		log.Println("UpdRoleHandler[prm.UpdRole] :", err.Error())
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}
	if queryRole.CreateTime != "" {
		c.String(http.StatusServiceUnavailable, "该角色名称已存在！")
		return
	}
	err = prm.UpdRoleOw(s.db)
	if err != nil {
		log.Println("UpdRoleHandler[prm.UpdRole] :", err.Error())
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}
	r, _ := json.Marshal(prm)
	c.String(http.StatusOK, string(r))
}

func (s *User) GetRoleByIdHandler(c *gin.Context) {
	prm := &UsRole{}
	var err error
	_ = err
	err = c.ShouldBind(prm)
	if err != nil {
		log.Println("GetRoleByIdHandler[c.ShouldBind] :", err.Error())
		c.String(http.StatusBadRequest, err.Error())
		return
	}
	if prm.Id == 0 {
		c.String(http.StatusBadRequest, "参数异常！")
		return
	}
	err = prm.GetRoleById(s.db, c)
	if err != nil {
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}
	err = prm.GetMenusByRoleId(s.db)
	if err != nil {
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}
	r, _ := json.Marshal(prm)
	c.String(http.StatusOK, string(r))
}

func (s *User) DelMenuHandler(c *gin.Context) {
	prm := &UsMenu{}
	var err error
	_ = err
	err = c.ShouldBind(prm)
	if err != nil {
		log.Println("DelMenuHandler[c.ShouldBind] :", err.Error())
		c.String(http.StatusBadRequest, err.Error())
		return
	}
	if prm.Id == 0 {
		c.String(http.StatusBadRequest, "请求参数错误!")
		return
	}
	count, err := prm.CountMenuByPid(s.db)
	if err != nil {
		c.String(http.StatusBadRequest, err.Error())
		return
	}
	if count > 0 {
		c.String(http.StatusBadRequest, "该菜单下面存在子集无法删除！!")
		return
	}
	err = prm.DelMenu(s.db, c)
	if err != nil {
		log.Println("DelMenuHandler[prm.DelMenu] :", err.Error())
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}
	r, _ := json.Marshal(prm)
	c.String(http.StatusOK, string(r))
}

func (s *User) AddUsOrganizationHandler(c *gin.Context) {
	prm := &UsOrganization{}
	var err error
	_ = err
	err = c.ShouldBind(prm)
	if err != nil {
		log.Println("AddUsOrganizationHandler[c.ShouldBind] :", err.Error())
		c.String(http.StatusBadRequest, err.Error())
		return
	}

	err = prm.AddUsOrganization(s.db, c)
	if err != nil {
		log.Println("AddUsOrganizationHandler[prm.AddUsOrganization] :", err.Error())
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}
	r, _ := json.Marshal(prm)
	c.String(http.StatusOK, string(r))
}

func (s *User) UpdUsOrganizationHandler(c *gin.Context) {
	prm := &UsOrganization{}
	var err error
	_ = err
	err = c.ShouldBind(prm)
	if err != nil {
		log.Println("UpdUsOrganizationHandler[c.ShouldBind] :", err.Error())
		c.String(http.StatusBadRequest, err.Error())
		return
	}

	err = prm.UpdUsOrganization(s.db, c)
	if err != nil {
		log.Println("UpdUsOrganizationHandler[prm.UpdUsOrganization] :", err.Error())
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}
	r, _ := json.Marshal(prm)
	c.String(http.StatusOK, string(r))
}

// UploadSignatureHandler 上传电子签章
func UploadSignatureHandler(c *gin.Context) {
	// 获取用户名
	userName := c.PostForm("userName")
	if userName == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "用户名不能为空"})
		return
	}

	// 获取上传的文件
	file, header, err := c.Request.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "获取文件失败"})
		return
	}
	defer file.Close()

	// 验证文件类型（只允许图片格式）
	contentType := header.Header.Get("Content-Type")
	if contentType != "image/jpeg" && contentType != "image/png" && contentType != "image/gif" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "只允许上传图片文件（JPEG、PNG、GIF）"})
		return
	}

	// 验证文件大小（最大5MB）
	if header.Size > 5*1024*1024 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "文件大小不能超过5MB"})
		return
	}

	// 读取文件数据
	fileData, err := io.ReadAll(file)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "读取文件失败"})
		return
	}

	// 生成文件名：用户名_时间戳.扩展名
	ext := filepath.Ext(header.Filename)
	if ext == "" {
		ext = ".png" // 默认扩展名
	}
	objectName := fmt.Sprintf("signatures/%s%s", userName, ext)

	// 上传到MinIO
	fileURL, err := common.UploadSignature(objectName, fileData, contentType)
	if err != nil {
		log.Printf("UploadSignatureHandler[UploadSignature]: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "上传文件失败"})
		return
	}

	// 更新用户表中的签章URL
	user := &UsUser{UserName: userName}
	err = user.UpdateSignatureURL(common.DB, fileURL)
	if err != nil {
		log.Printf("UploadSignatureHandler[UpdateSignatureURL]: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "更新用户签章信息失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "上传成功",
		"data": gin.H{
			"url":        fileURL,
			"objectName": objectName,
		},
	})
}

// DeleteSignatureHandler 删除用户电子签章
func DeleteSignatureHandler(c *gin.Context) {
	// 获取用户名
	userName := c.Query("userName")
	if userName == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "用户名不能为空"})
		return
	}

	// 先获取当前的签章URL
	user := &UsUser{UserName: userName}
	currentSignatureURL, err := user.GetSignatureURL(common.DB)
	if err != nil {
		if err.Error() == "用户不存在" {
			c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
			return
		}
		log.Printf("DeleteSignatureHandler[GetSignatureURL]: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取签章信息失败"})
		return
	}

	// 如果没有签章，直接返回成功
	if currentSignatureURL == "" {
		c.JSON(http.StatusOK, gin.H{
			"code":    0,
			"message": "用户暂无电子签章",
		})
		return
	}

	// 从URL中提取对象名
	objectName := ""
	if strings.Contains(currentSignatureURL, "signature/") {
		// 解析URL获取对象名
		parts := strings.Split(currentSignatureURL, "signature/")
		if len(parts) > 1 {
			objectName = "signature/" + parts[len(parts)-1]
			// 移除查询参数
			if idx := strings.Index(objectName, "?"); idx != -1 {
				objectName = objectName[:idx]
			}
		}
	}

	// 删除MinIO中的文件
	if objectName != "" {
		err = common.DeleteSignature(objectName)
		if err != nil {
			log.Printf("DeleteSignatureHandler[DeleteSignature]: %v", err)
			// 继续执行，即使文件删除失败也要清除数据库记录
		}
	}

	// 更新用户表，清空签章URL
	err = user.UpdateSignatureURL(common.DB, "")
	if err != nil {
		log.Printf("DeleteSignatureHandler[UpdateSignatureURL]: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "更新用户签章信息失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "删除成功",
	})
}

// GetSignatureHandler 获取用户电子签章
func GetSignatureHandler(c *gin.Context) {
	// 获取用户名
	userName := c.Query("userName")
	if userName == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "用户名不能为空"})
		return
	}

	// 查询用户签章URL
	user := &UsUser{UserName: userName}
	signatureURL, err := user.GetSignatureURL(common.DB)
	if err != nil {
		if err.Error() == "用户不存在" {
			c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
			return
		}
		log.Printf("GetSignatureHandler[GetSignatureURL]: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取签章信息失败"})
		return
	}

	// 如果签章URL为空，返回空数据
	if signatureURL == "" {
		c.JSON(http.StatusOK, gin.H{
			"code":    0,
			"message": "用户暂无电子签章",
			"data": gin.H{
				"hasSignature": false,
				"url":          "",
			},
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "获取成功",
		"data": gin.H{
			"hasSignature": true,
			"url":          signatureURL,
		},
	})
}

func (s *User) GetAllMenuListHandler(c *gin.Context) {
	prm := &UsMenu{}
	var err error
	_ = err
	err = c.ShouldBind(prm)
	if err != nil {
		log.Println("GetAllMenuListHandler[c.ShouldBind] :", err.Error())
		c.String(http.StatusBadRequest, err.Error())
		return
	}
	err = prm.GetAllMenuList(s.db, c)
	if err != nil {
		log.Println("GetAllMenuListHandler[prm.GetAllMenuList] :", err.Error())
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}

	menuAction := &UsMenuAction{}
	err = menuAction.getMenuAction(s.db)
	if err != nil {
		log.Println("GetMenuActionHandler[prm.GetMenuList] :", err.Error())
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}

	for _, v := range prm.List {
		for _, m := range menuAction.List {
			if v.Id == m.MenuId {
				v.ActionList = append(v.ActionList, m)
			}
		}
	}

	r, _ := json.Marshal(prm)
	c.String(http.StatusOK, string(r))
}

func (s *User) AddMenuHandler(c *gin.Context) {
	prm := &UsMenu{}
	var err error
	_ = err
	err = c.ShouldBind(prm)
	if err != nil {
		log.Println("AddMenuHandler[c.ShouldBind] :", err.Error())
		c.String(http.StatusBadRequest, err.Error())
		return
	}

	tx := s.db.NewSession()
	defer tx.Close()
	err = tx.Begin()
	if err != nil {
		log.Println("AddMenuHandler[tx.Begin]:", err.Error())
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}

	err = prm.addMenu(tx)
	if err != nil {
		log.Println("AddMenuHandler[prm.AddMenu] :", err.Error())
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}

	for _, v := range prm.ActionList {
		v.MenuId = prm.Id
	}

	err = prm.addMenuActions(tx)
	if err != nil {
		log.Println("AddMenuHandler[tx.Commit]:", err.Error())
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}

	err = tx.Commit()
	if err != nil {
		tx.Rollback()
		log.Println("AddMenuHandler[tx.Commit]:", err.Error())
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}
	r, _ := json.Marshal(prm)
	c.String(http.StatusOK, string(r))
}

func (s *User) UpdMenuHandler(c *gin.Context) {
	prm := &UsMenu{}
	var err error
	_ = err
	err = c.ShouldBind(prm)
	if err != nil {
		log.Println("UpdMenuHandler[c.ShouldBind] :", err.Error())
		c.String(http.StatusBadRequest, err.Error())
		return
	}

	tx := s.db.NewSession()
	defer tx.Close()
	err = tx.Begin()
	if err != nil {
		log.Println("UpdMenuHandler[tx.Begin]:", err.Error())
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}

	err = prm.updMenu(tx)
	if err != nil {
		log.Println("UpdMenuHandler[prm.UpdMenu] :", err.Error())
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}

	err = prm.delMenuActions(tx)
	if err != nil {
		log.Println("UpdMenuHandler[prm.UpdMenu] :", err.Error())
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}

	for _, v := range prm.ActionList {
		v.MenuId = prm.Id
	}

	err = prm.addMenuActions(tx)
	if err != nil {
		log.Println("AddMenuHandler[tx.Commit]:", err.Error())
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}

	err = tx.Commit()
	if err != nil {
		tx.Rollback()
		log.Println("AddMenuHandler[tx.Commit]:", err.Error())
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}

	r, _ := json.Marshal(prm)
	c.String(http.StatusOK, string(r))
}

func (s *User) ResetPasswordHandler(c *gin.Context) {
	prm := &UsUser{}
	var err error
	_ = err
	err = c.ShouldBind(prm)
	if err != nil {
		log.Println("ResetPasswordHandler[c.ShouldBind] :", err.Error())
		c.String(http.StatusBadRequest, err.Error())
		return
	}
	prm.Password = common.EncodeMD5("Gb123456!") //默认初始密码Gb123456!
	prm.Password = strings.ToUpper(prm.Password)
	err = prm.UpdPassword(s.db, c)
	if err != nil {
		log.Println("ResetPasswordHandler[prm.UpdPassword] :", err.Error())
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}
	r, _ := json.Marshal(prm)
	c.String(http.StatusOK, string(r))
}

func (s *User) GetUsOrganizationListHandler(c *gin.Context) {
	prm := &UsOrganization{}
	var err error
	_ = err
	err = c.ShouldBind(prm)
	if err != nil {
		log.Println("GetUsOrganizationListHandler[c.ShouldBind] :", err.Error())
		c.String(http.StatusBadRequest, err.Error())
		return
	}
	err = prm.getUsOrgTree(s.db)
	if err != nil {
		log.Println("GetUsOrganizationListHandler[prm.GetUsOrganizationList] :", err.Error())
		c.String(http.StatusServiceUnavailable, err.Error())
		return
	}
	r, _ := json.Marshal(prm)
	c.String(http.StatusOK, string(r))
}

type Info struct {
	UserName string
	RealName string
}

type OrgInfo struct {
	Id    int64
	Name  string
	Users []*Info
}

func GetUserOrgListHandler(c *gin.Context) {
	orgs := make([]*OrgInfo, 0)

	err := common.DB.SQL("select id,name from us_organization").Find(&orgs)
	if err != nil {
		log.Println("GetUserOrgListHandler: ", err.Error())
		c.JSON(http.StatusInternalServerError, gin.H{"Code": 1, "Msg": err.Error()})
		return
	}

	for _, org := range orgs {
		org.Users = make([]*Info, 0)
		err = common.DB.SQL("SELECT t2.user_name,t2.real_name from us_user_organization t1 LEFT JOIN us_user t2 on t1.user_id = t2.user_name WHERE t1.org_id = ?", org.Id).Find(&org.Users)
		if err != nil {
			log.Println("GetUserOrgListHandler users: ", err.Error())
			c.JSON(http.StatusInternalServerError, gin.H{"Code": 1, "Msg": err.Error()})
			return
		}
	}

	c.JSON(http.StatusOK, gin.H{"Code": 0, "Data": orgs, "Msg": "成功"})
}

// ChangePasswordHandler 修改密码处理器（新创建，避免与现有冲突）
func (s *_User) ChangePasswordHandler(c *gin.Context) {
	// 定义请求结构体
	type ChangePasswordRequest struct {
		NewPassword string `json:"newPassword" binding:"required"`
	}

	req := &ChangePasswordRequest{}
	err := c.ShouldBindJSON(req)
	if err != nil {
		log.Println("ChangePasswordHandler[c.ShouldBindJSON] :", err.Error())
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "参数错误"})
		return
	}

	// 从JWT中获取当前用户名
	username, exists := c.Get("username")
	if !exists {
		log.Println("ChangePasswordHandler: 无法获取用户信息")
		c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "未授权"})
		return
	}

	// 加密新密码
	encryptedPassword := common.EncodeMD5(req.NewPassword)
	encryptedPassword = strings.ToUpper(encryptedPassword)

	// 更新数据库
	user := &UsUser{
		UserName: username.(string),
		Password: encryptedPassword,
	}

	err = user.UpdPassword(s.db, c)
	if err != nil {
		log.Println("ChangePasswordHandler[UpdPassword] :", err.Error())
		c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "msg": "密码更新失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "密码修改成功"})
}

func RegisterRoutes(group *gin.RouterGroup) {
	group.POST("/user/getUserForSelect", GetUserOrgListHandler)
	group.POST("/user/uploadSignature", UploadSignatureHandler)
	group.GET("/user/getSignature", GetSignatureHandler)
	group.DELETE("/user/deleteSignature", DeleteSignatureHandler)
	// 新添加的密码修改路由
	userService := NewUser(common.DB)
	group.POST("/user/changePassword", userService.ChangePasswordHandler)
}
